﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using System.IO;

namespace DreamShieldPublishRetriever
{
    static class Program
    {
        public static bool DebugRun { get; set; }

        /// <summary>
        /// Point d'entrée principal de l'application.
        /// </summary>
        [STAThread]
        static void Main(string[] args)
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            string xml_file = null;
            if (args.Length > 0)
                xml_file = args[0];
            else
                xml_file = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), "Product.xml");

            if (!File.Exists(xml_file))
            {
                MessageBox.Show(String.Format("Le fichier {0} est introuvable", xml_file), "Attention", MessageBoxButtons.OK, MessageBoxIcon.Warning);
            }
            else
            {
                ProductXml xml_obj = null;
                using (FileStream fs = new FileStream(xml_file, FileMode.Open, FileAccess.Read))
                {
                    try
                    {
                        xml_obj = (ProductXml)ProductXml.GetSerializer().Deserialize(fs);
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(String.Format("Le fichier {0} n'est pas valide.\n{1}", xml_file, ex.Message),
                            "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        return;
                    }
                }

                /* Pour désactiver la gestion de l'erreur, on 
                 * regarde si on roule dans VS
                 */
                DebugRun =
                    System.Diagnostics.Process.GetCurrentProcess().ProcessName.Contains("vshost")
                    || System.Diagnostics.Process.GetCurrentProcess().ProcessName == "devenv";

                if (DebugRun)
                {
                    Application.Run(new MainForm(xml_obj));
                }
                else
                {
                    try
                    {
                        Application.Run(new MainForm(xml_obj));
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(String.Format("Erreur critique dans le programme :\n{0}", ex),
                            "Erreur", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
            }
        }
    }
}
